<template>
  <div class="allcontent">
    <div class="search">
      <el-form   @submit.native.prevent   size="small"  ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="标题" prop="title">
          <el-input
              v-model="queryParams.title"
              placeholder="标题"
              clearable
              @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="介绍" prop="introduce">
          <el-input
                    v-model="queryParams.introduce"
                    placeholder="介绍"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
        </el-form-item>
        <el-form-item label="分类" prop="classicId">
          <el-select clearable  v-model="queryParams.classicId" placeholder="请选择分类"  style="width: 200px;">
            <el-option v-for="item in classiclist" :key="item.name" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="queryParams.auditStatus" style="width: 200px;">
            <el-option v-for="item in audit_status" :value="item.dataValue" :label="item.dataName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button plain type="warning"  @click="handleResetQuery(queryFormRef)">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

<!--    <el-button  plain icon="Edit"  size="small"
                v-if="userStore.hasPermission('background:post:add')"
                type="success"
                @click="handleOpenDialog()"
    >
      新增
    </el-button>-->
<!--    <el-button  plain icon="Edit"  size="small"
                :disabled="selectionIds.length === 0"
                v-if="userStore.hasPermission('background:post:update')"
                type="primary"
                @click="handleOpenDialog()"
    >
      修改
    </el-button>-->
    <el-button  plain icon="Delete"  size="small"
                v-if="userStore.hasPermission('background:post:remove')"
                type="danger"
                :disabled="selectionIds.length === 0"
                @click="handleDelete()"
    >
      删除
    </el-button>
    <div class="el-table">
      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
            key="createTime"
            label="创建时间"
            prop="createTime"
            min-width="150"
            align="center"
        >
          <template #default="scope">
            {{formatTimestamp(scope.row.createTime)}}
          </template>
        </el-table-column>
<!--        <el-table-column
            key="cover"
            label="封面"
            prop="cover"
            min-width="150"
            align="center"
        >
          <template #default="scope">
            <el-image    :src="baseUrl+scope.row.cover" style="width: 50px;height: 50px"/>
          </template>
        </el-table-column>-->
        <el-table-column
            show-overflow-tooltip
            key="title"
            label="标题"
            prop="title"
            min-width="150"
            align="center"
        />
        <el-table-column
            show-overflow-tooltip
            key="introduce"
            label="介绍"
            prop="introduce"
            min-width="150"
            align="center"
        />
        <el-table-column
            show-overflow-tooltip
            key="content"
            label="内容"
            prop="content"
            min-width="150"
            align="center"
        />
        <el-table-column
            show-overflow-tooltip
            key="classicId"
            label="分类"
            prop="classicName"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="auditStatus"
            label="审核状态"
            prop="auditStatus"
            min-width="150"
            align="center"
        >
          <template #default="scope">
            <div v-for="item in audit_status">
              <el-tag v-if="scope.row.auditStatus == item.dataValue">
                {{item.dataName}}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            show-overflow-tooltip
            key="refuseReason"
            label="拒绝理由"
            prop="refuseReason"
            min-width="150"
            align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
                v-if="userStore.hasPermission('background:post:update')"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><InfoFilled /></template>
              详情
            </el-button>
            <el-button
                v-if="userStore.hasPermission('background:post:remove')"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="el-pager">
      <el-pagination layout="total,sizes,prev, pager, next,jumper" :total="total"
                     :page-sizes="[10,20,30,40,50]" :pager-count="11"
                     size="small"  background  class="mt-4" :current-page="currentPage"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
    <!-- 帖子表单弹窗 -->
    <el-drawer
        v-model="dialog.visible"
        :title="dialog.title"
        size="40%"
        @close="handleCloseDialog"
    >
      <el-form disabled size="small" ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
<!--        <el-form-item label="封面" prop="cover">
          <ImageUpload :img="formData.cover" :t="new Date().getTime()" v-model="formData.cover"
                       @imgData="getImg"></ImageUpload>
        </el-form-item>-->
        <el-form-item label="标题" prop="title">
          <el-input
              v-model="formData.title"
              placeholder="标题"
          />
        </el-form-item>
        <el-form-item label="介绍" prop="introduce">
          <el-input type="textarea"
                    v-model="formData.introduce"
                    placeholder="介绍"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <MavonEditor  v-model="formData.content" :content="formData.content"
                        @contentData="getContentData"></MavonEditor>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="classicId">
              <el-select clearable  v-model="formData.classicId" placeholder="请选择分类"  style="width: 200px;">
                <el-option  v-for="item in classiclist"  :key="item.name" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select clearable v-model="formData.auditStatus" style="width: 200px;">
                <el-option v-for="item in audit_status" :value="item.dataValue" :label="item.dataName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="拒绝理由" prop="refuseReason" v-if="formData.auditStatus == '2'">
          <el-input
              v-model="formData.refuseReason"
              placeholder="拒绝理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="false" size="small" icon="Edit" type="primary" @click="handleSubmit()">确定</el-button>
          <el-button size="small" icon="Close" @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {page,info,edit,save,remove} from "@/api/forum/post";
import {list} from '@/api/forum/classic.ts'
import {ElMessage,ElMessageBox,ElTree,ElTable,type FormInstance} from 'element-plus'
import {ref,reactive,watch,onMounted} from 'vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import MultiImageUpload from '@/components/MultiImageUpload/index.vue'
import MavonEditor from '@/components/MavonEditor/index.vue'
import {useUserStore} from '@/stores/user.ts'
import {formatTimestamp} from '@/utils/date.ts'
import {InfoFilled} from "@element-plus/icons-vue";
const baseUrl = import.meta.env.VITE_API_URL
const userStore = useUserStore()
const queryFormRef = ref<FormInstance>();
const dataFormRef = ref();
const getImg=(val)=>{
  formData.value.cover=val
}
const audit_status=userStore.getDictData('audit_status');
const getImgs=(val)=>{
}
const getContentData=(val)=>{
  formData.value.content=val
}
const loading = ref(false);
const selectionIds = ref<number[]>([]);
const total = ref(0);

const currentPage = ref(1)
const handleSizeChange = (val: number) => {
  queryParams.value.limit= val;
  handleQuery();
}
const handleCurrentChange = (val: number) => {
  currentPage.value= val;
  queryParams.value.page= val;
  handleQuery();
}

const queryParams = ref({
  page: 1,
  limit: 10,
  title:null,
  introduce:null,
  content:null,
  classicId:null,
  auditStatus:null,
});

// 帖子表格数据
const tableData = ref([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
// 帖子表单数据
const formData = ref({
  id:null,
  cover:null,
  title:null,
  introduce:null,
  content:null,
  classicId:null,
  auditStatus:null,
  refuseReason:null,
});

// 帖子表单校验规则
const rules = reactive({
  cover: [{ required: true, message: "请输入封面", trigger: "blur" }],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  introduce: [{ required: true, message: "请输入介绍", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
  classicId: [{ required: true, message: "请输入分类ID", trigger: "blur" }],
});

/** 查询帖子 */
const handleQuery=()=> {
  loading.value = true;
  page(queryParams.value)
      .then((res) => {
        tableData.value = res.data.list;
        total.value = res.data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

/** 重置帖子查询 */
const handleResetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
const handleSelectionChange=(selection: any)=> {
  selectionIds.value = selection.map((item: any) => item.id);
}

/** 打开帖子弹窗 */
const handleOpenDialog=(id: number)=>{
  dialog.visible = true;
  if (id) {
    dialog.title = "修改帖子";
    info(id).then((res) => {
      Object.assign(formData.value, res.data);
    });
  }else if(selectionIds.value.length > 0){
    if(selectionIds.value.length > 1){
      ElMessage({
        type: 'warning',
        message: '编辑只能选择一行',
      })
      return;
    }
    dialog.title = "修改岗位";
    info(selectionIds.value[0]).then((res) => {
      Object.assign(formData.value, res.data);
    });
  } else {
    dialog.title = "新增帖子";
  }
}

/** 提交帖子表单 */
const handleSubmit=()=> {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.value.id;
      if (id) {
        edit(formData.value)
            .then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleResetQuery(queryFormRef.value);
            })
            .finally(() => (loading.value = false));
      } else {
        save(formData.value)
            .then(() => {
              ElMessage.success("新增成功");
              handleCloseDialog();
              handleResetQuery(queryFormRef.value);
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭帖子弹窗 */
const handleCloseDialog=()=> {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.value.id = undefined;
}

/** 删除帖子 */
const handleDelete=(id?: number)=> {
  const ids = id ?  [id] : selectionIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      () => {
        loading.value = true;
        remove(ids)
            .then(() => {
              ElMessage.success("删除成功");
              handleResetQuery(queryFormRef.value);
            })
            .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消删除");
      }
  );
}

onMounted(() => {
  handleQuery();
  getClassicList()
});
const classiclist = ref([])
const getClassicList=()=>{
  list({}).then((res) => {
    classiclist.value = res.data
  })
}
</script>
<style scoped>
.dialog-footer{
  text-align: center;
}
.search{
  margin-bottom: 10px;
}
.el-pager{
  padding: 1%;
  justify-content: right;
}
.allcontent{
  height: 65vh;
  position: relative;
}
.el-table{
  max-height:70%;
  overflow: auto;
}
.el-table::-webkit-scrollbar{
  display: none;
}
</style>
